package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class _94_BinaryTreeInorderTraversal {
    public static void main(String[] args) {
        Solution solution = new _94_BinaryTreeInorderTraversal().new Solution();
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    // 递归的写法要牢记
    // 递归
    class Solution {
        private void inorderTraversal(List<Integer> res, TreeNode root) {
            if (root == null) {
                return;
            }
            inorderTraversal(res, root.left);
            res.add(root.val);
            inorderTraversal(res, root.right);
        }

        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            inorderTraversal(res, root);
            return res;
        }
    }

    // 迭代
    class Solution2 {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            Deque<TreeNode> stack = new LinkedList<>();
            TreeNode cur = root;
            while (!stack.isEmpty() || cur != null) {
                while (cur != null) {
                    stack.push(cur);
                    cur = cur.left;
                }
                cur = stack.peek();
                stack.pop();
                res.add(cur.val);
                cur = cur.right;
            }
            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}